<!--
 * @Author: 李小晴 2689279066@qq.com
 * @Date: 2023-02-08 10:32:35
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-04-05 12:44:09
 * @FilePath: \zhmc_pc\sys\src\components\Table\src\Table.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { ref, watch, reactive } from 'vue'
import { Search, RefreshLeft } from '@element-plus/icons-vue'
import {
  ElTableColumn,
  ElTable,
  ElPagination,
  ElCol,
  ElRow,
  ElCheckbox,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton
} from 'element-plus'
import type { FormInstance } from 'element-plus'

// import { zcAssetListAdminApi } from '@/api/fa/earcon'
import { zcAssetListAdminApi } from '@/api/fa/earcon'

const ruleFormRef = ref<FormInstance>()
let allCheck = ref(false)
let selectData = ref([])
let noSelectData = ref([])
const total = ref(0)
let num = ref(0)
const props = defineProps({
  id: {
    type: Number,
    default: () => null
  },
  selectData: {
    type: Array,
    default: () => null
  },
  allCheck: {
    type: Boolean,
    default: () => null
  },
  breed: {
    type: String,
    default: () => null
  },
  breedSub: {
    type: String,
    default: () => null
  }
})
console.log(allCheck, 'allCheck')
console.log(selectData, 'selectData')
let assetsData = ref([])
const multipleTable = ref<InstanceType<typeof ElTable>>()

const page = ref(1)
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const disabled = ref(false)

const getList = async (val) => {
  let res
  if (val) {
    res = await zcAssetListAdminApi({
      pasture_org_id: props.id,
      pageSize: pageSize4.value,
      pageNo: page.value,
      customer_name: val.customer_name,
      breed: props.breed,
      breed_sub: props.breedSub,
      select_type: '2'
      // earcon_code: val
    })
      .catch(() => {})
      .finally(() => {})
  } else {
    res = await zcAssetListAdminApi({
      pasture_org_id: props.id,
      pageSize: pageSize4.value,
      pageNo: page.value,
      breed: props.breed,
      breed_sub: props.breedSub,
      select_type: '2'
    })
      .catch(() => {})
      .finally(() => {})
  }

  if (res) {
    assetsData.value = res.data
    total.value = res.count
    // allCheck.value = props.allCheck
    // console.log(props.allCheck, 'allCheck.value')
    setTimeout(() => {
      if (allCheck.value) {
        num.value = total.value - props.selectData.length
        let newArr = assetsData.value.filter(
          (x) => !noSelectData.value.some((item) => x.id === item.id)
        )
        newArr.forEach((row) => {
          multipleTable.value.toggleRowSelection(row, true)
        })
      } else {
        // setTimeout(() => {
        //   selectData.value.forEach((row) => {
        //     multipleTable.value.toggleRowSelection(row, true)
        //   })
        // }, 0)
      }
    }, 0)
  }
}

const init = async () => {
  // 列表查询
  allCheck.value = props.allCheck
  if (allCheck.value) {
    await getList()
    noSelectData.value = props.selectData
    if (noSelectData.value.length > 0) {
      // 去重
      let newArr = assetsData.value.filter(
        (x) => !noSelectData.value.some((item) => x.id === item.id)
      )
      newArr.forEach((row) => {
        multipleTable.value.toggleRowSelection(row, true)
      })
    } else {
      assetsData.value.forEach((row) => {
        multipleTable.value.toggleRowSelection(row, true)
      })
    }
  } else {
    num.value = props.selectData ? props.selectData.length : 0
    selectData.value = props.selectData
    setTimeout(() => {
      console.log(selectData.value, 'selectData.value')
      if (selectData.value && selectData.value.length > 0) {
        selectData.value.forEach((row) => {
          multipleTable.value.toggleRowSelection(row, true)
        })
      } else {
        selectData.value = []
      }
    }, 0)
    await getList()
  }
}

init()

// 分页
const handleCurrentChange = (val) => {
  page.value = val
  getList()
  currentPage4.value = val
}

const handleSizeChange = () => {
  getList()
}

const getRowKeys = (row) => {
  return row.id
}
const handleSelect = (val) => {
  selectData.value = val
}
const select = (val, row) => {
  if (allCheck.value) {
    num.value = num.value - 1
    noSelectData.value.push(row)
  } else {
    num.value = val.length
    selectData.value.filter((item, index) => {
      if (item.id == row.id) {
        selectData.value.splice(index, 1)
      } else {
      }
    })
  }
  console.log(num, 'num')
}
// 全选当前页
const handleSelectAll = (val) => {
  num.value = selectData.value.length
  selectData.value = val
}
// 全选
const onChangeCheckAll = (val) => {
  if (val) {
    noSelectData.value = []
    // selectData.value = []
    num.value = total.value
    selectData.value.length = total.value
    assetsData.value.forEach((row) => {
      multipleTable.value.toggleRowSelection(row, true)
    })
  } else {
    num.value = 0
    multipleTable.value.clearSelection()
  }
}
// var newArr=arr.map((v)=> v.id)
defineExpose({
  selectData,
  noSelectData,
  allCheck,
  num
})

const ruleForm = reactive({
  earcon_code: '',
  asset_code: ''
  // breed_sub: '',
  // breed: ''
})

const rules = reactive({
  // pass: [{ validator: validatePass, trigger: 'blur' }],
  // checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  // age: [{ validator: checkAge, trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  // if (!formEl) return
  // formEl.validate((valid) => {
  //   if (valid) {
  //     console.log('submit!')
  //   } else {
  //     console.log('error submit!')
  //     return false
  //   }
  // })
  allCheck.value = ''
  multipleTable.value.clearSelection()
  // props.selectData = ''
  console.log(formEl, 'formEl')
  getList(ruleForm)
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

watch(
  () => multipleTable,
  (value) => {
    if (!value) return
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <div>
    <ElForm
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <ElFormItem class="formInput" label="耳标编号" prop="earcon_code">
        <ElInput v-model="ruleForm.earcon_code" placeholder="请输入" />
      </ElFormItem>
      <ElFormItem class="formInput" label="资产编号" prop="asset_code">
        <ElInput v-model="ruleForm.asset_code" placeholder="请输入" />
      </ElFormItem>
      <ElFormItem class="formButton">
        <ElButton type="primary" @click="submitForm(ruleForm)" :icon="Search">查询</ElButton>
        <ElButton @click="resetForm(ruleFormRef)" :icon="RefreshLeft">重置</ElButton>
      </ElFormItem>
    </ElForm>
    <!-- <span>已选择 {{ num }}条资产</span> -->
    <ElTable
      ref="multipleTable"
      :data="assetsData"
      :row-key="getRowKeys"
      border
      @select-all="handleSelectAll"
      @selection-change="handleSelect"
      @select="select"
    >
      <ElTableColumn :value="selectData" type="selection" :reserve-selection="true" width="80" />
      <ElTableColumn
        prop="pasture_org_name"
        align="center"
        label="牧场"
        min-width="150px"
        show-overflow-tooltip
      />
      <ElTableColumn
        prop="earcon_code"
        align="center"
        label="耳标编号"
        min-width="150px"
        show-overflow-tooltip
      />
      <ElTableColumn
        prop="asset_code"
        align="center"
        label="资产编号"
        min-width="150px"
        show-overflow-tooltip
      />
    </ElTable>

    <ElRow>
      <ElCol :span="3">
        <ElCheckbox class="mt-2px" @change="onChangeCheckAll" v-model="allCheck" label="全选所有" />
      </ElCol>
      <ElCol :span="4">
        <span>已选择 {{ num }}条资产</span>
      </ElCol>
      <ElCol class="text-left" :span="17">
        <ElPagination
          v-model:current-page="currentPage4"
          v-model:page-size="pageSize4"
          :page-sizes="[10, 50, 100, 1000]"
          :disabled="disabled"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-size="10"
          :total="total"
          style="float: right"
        />
      </ElCol>
    </ElRow>
  </div>
</template>
<style lang="less" scoped>
.demo-ruleForm .formInput {
  display: inline-flex;
  vertical-align: middle;
  margin-right: 32px;
}
:deep(.el-form-item__label) {
  width: 70px !important;
}
.formButton {
  display: inline-flex;
  vertical-align: middle;
}
.el-row .el-col-4 {
  line-height: 36px;
}
</style>
